package cn.miwu52.homeworkerp.Controller;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.huawei.hms.hmsscankit.ScanUtil;
import com.huawei.hms.ml.scan.HmsScan;
import com.huawei.hms.ml.scan.HmsScanAnalyzerOptions;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.miwu52.homeworkerp.R;
import cn.miwu52.homeworkerp.bean.Entrepot;
import cn.miwu52.homeworkerp.bean.Product;
import cn.miwu52.homeworkerp.dao.EntrepotDao;
import cn.miwu52.homeworkerp.dao.ProductDao;

//添加商品的视图操作
public class addProductActivity extends AppCompatActivity {
    private EntrepotDao entrepotDao;
    private ListView listView;
    private ProductDao productDao;
    private Spinner product_list;
    private TextView spinnerEntrepotId;
    private TextView imageUrl;
    private EditText product_id;
    private EditText product_name;
    private String authorization = null;
    private static final int CAMERA_REQ_CODE = 111;
    private static final int REQUEST_CODE_SCAN_ONE = 0X01;

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Log.i("发起扫码请求", requestCode + "" + grantResults);
        if (requestCode == CAMERA_REQ_CODE && grantResults.length == 2 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
            HmsScanAnalyzerOptions hmsScanAnalyzerOptions = new HmsScanAnalyzerOptions.Creator().
                    setHmsScanTypes(HmsScan.CODE128_SCAN_TYPE, HmsScan.CODE39_SCAN_TYPE, HmsScan.CODE93_SCAN_TYPE, HmsScan.EAN13_SCAN_TYPE).create();
            ScanUtil.startScan(this, REQUEST_CODE_SCAN_ONE, hmsScanAnalyzerOptions);
        }
    }

    //接收返回值
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_SCAN_ONE) {
            HmsScan parcelableExtra = data.getParcelableExtra(ScanUtil.RESULT);
            if (parcelableExtra != null) {
                //处理出库 parcelableExtra.getOriginalValue().trim()
                MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.saomachenggong);
                mediaPlayer.start();
                product_id.setText(parcelableExtra.getOriginalValue().trim());

                Thread thread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        authorization = HttpRequest.post("https://jumbarcode.market.alicloudapi.com/bar-code/query")
                                .header("Authorization", "APPCODE 8eab40279ca54130bedc849e9e206ba7")
                                .timeout(3000)
                                .form("code", "0" + parcelableExtra.getOriginalValue().trim())
                                .execute()
                                .body();
                        Log.i("线程请求", authorization);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                JSONObject entries = JSONUtil.parseObj(authorization);
                                JSONObject data1 = JSONUtil.parseObj(entries.getObj("data"));
                                System.out.println(data1.getStr("img"));
                                product_name.setText(data1.getStr("goodsName"));
                                imageUrl.setText(StrUtil.replace(data1.getStr("img"), "http://", "https://"));
                                System.out.println(parcelableExtra.getOriginalValue().trim());
                            }
                        });
                    }
                }
                );
                thread.start();

            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_product);
        entrepotDao = new EntrepotDao(this);
        Button addProductButton = findViewById(R.id.addProductButton);//添加商品按钮
        productDao = new ProductDao(this);
        product_id = findViewById(R.id.product_id);//商品条码
        product_name = findViewById(R.id.product_name);//商品名称
        product_list = findViewById(R.id.product_spinner);//仓库列表
        listView = findViewById(R.id.product_list);
        imageUrl = findViewById(R.id.imageAddUrl);
        ImageView qrcode = findViewById(R.id.qrcode);
        updateSpinnerList();


        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                TextView product_id = view.findViewById(R.id.product_id);
                TextView product_name = view.findViewById(R.id.product_name);
                AlertDialog alertDialog = new AlertDialog.Builder(addProductActivity.this)
                        .setIcon(R.drawable.erp)
                        .setTitle("询问")
                        .setMessage("请选择你的操作")
                        .setNegativeButton("删除", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                //点击删除按钮
                                AlertDialog alertDialog1 = new AlertDialog.Builder(addProductActivity.this)
                                        .setIcon(R.drawable.erp)
                                        .setTitle("警告")
                                        .setMessage("确定要删除【" + product_name.getText().toString() + "】吗？")
                                        .setNegativeButton("确定", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialogInterface, int i) {
                                                //执行删除操作
                                                if (productDao.deleteProductById(product_id.getText().toString())) {
                                                    Toast.makeText(getApplicationContext(), "删除成功", Toast.LENGTH_SHORT).show();
                                                    return;
                                                }
                                                Toast.makeText(getApplicationContext(), "删除失败", Toast.LENGTH_SHORT).show();
                                            }
                                        })
                                        .setPositiveButton("取消", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialogInterface, int i) {

                                            }
                                        }).create();
                                alertDialog1.show();

                            }
                        })
                        .setPositiveButton("修改", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                //点击修改按钮
                                View inflate = getLayoutInflater().inflate(R.layout.alertdialog_edit, null);
                                EditText newEntrepotName = inflate.findViewById(R.id.newEntrepotName);
                                AlertDialog alertDialog1 = new AlertDialog.Builder(addProductActivity.this)
                                        .setIcon(R.drawable.erp)
                                        .setTitle("提示")
                                        .setMessage("请输入新名字")
                                        .setView(inflate)
                                        .setNegativeButton("保存", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialogInterface, int i) {
                                                //修改
                                                if (productDao.changeProductNameById(newEntrepotName.getText().toString(), product_id.getText().toString())) {
                                                    Toast.makeText(getApplicationContext(), "修改成功", Toast.LENGTH_SHORT).show();
                                                    return;
                                                }
                                                Toast.makeText(getApplicationContext(), "修改失败", Toast.LENGTH_SHORT).show();
                                            }
                                        })
                                        .setPositiveButton("取消", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialogInterface, int i) {
                                                //取消
                                            }
                                        }).create();
                                alertDialog1.show();
                            }
                        }).create();
                alertDialog.show();
                return true;
            }
        });

        product_list.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                spinnerEntrepotId = product_list.getSelectedView().findViewById(R.id.spinnerEntrepotId);
                updateListView(Integer.parseInt(spinnerEntrepotId.getText().toString()));
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        qrcode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE}, CAMERA_REQ_CODE);
                }
            }
        });

        addProductButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                spinnerEntrepotId = product_list.getSelectedView().findViewById(R.id.spinnerEntrepotId);
                if (product_name.getText().toString().equals("") || product_id.getText().toString().equals("")) {
                    Toast.makeText(getApplicationContext(), "请输入当前商品对应的所有信息", Toast.LENGTH_SHORT).show();
                } else {
                    if (productDao.isProductById(product_id.getText().toString().trim())) {
                        Product product = new Product(product_id.getText().toString().trim()
                                , product_name.getText().toString()
                                , 0
                                , 0
                                , 0
                                , Integer.parseInt(spinnerEntrepotId.getText().toString())
                                , imageUrl.getText().toString());
                        Log.i("添加商品", product.toString());
                        boolean b = productDao.insertProduct(product);
                        if (b) {
                            updateListView(Integer.parseInt(spinnerEntrepotId.getText().toString()));
                            Toast.makeText(getApplicationContext(), "添加成功", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(getApplicationContext(), "添加失败", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(getApplicationContext(), "商品ID重复，禁止添加", Toast.LENGTH_SHORT).show();
                    }

                }
            }
        });


    }

    //更新商品列表
    public void updateListView(Integer id) {
        //获取查询结果
        List<Product> productByName = productDao.findProductByEntrepotId(id);
        //处理包装查询结果
        ArrayList<Map<String, Object>> maps = new ArrayList<>();
        for (Product product : productByName) {
            HashMap<String, Object> stringObjectHashMap = new HashMap<>();
            stringObjectHashMap.put("product_name", product.getName());
            stringObjectHashMap.put("sumInEntrepot", product.getSumInEntrepot());
            stringObjectHashMap.put("sumOutEntrepot", product.getSumOutEntrepot());
            stringObjectHashMap.put("InEntrepot", product.getInEntrepot());
            stringObjectHashMap.put("entrepot", product.getEntrepotId());
            stringObjectHashMap.put("product_id", product.getId());
            maps.add(stringObjectHashMap);
        }
        String[] from = {"product_name", "sumInEntrepot", "sumOutEntrepot", "InEntrepot", "entrepot", "product_id"};
        int[] to = {R.id.product_name, R.id.sumInEntrepot, R.id.sumOutEntrepot, R.id.InEntrepot, R.id.entrepot, R.id.product_id};
        SimpleAdapter simpleAdapter = new SimpleAdapter(addProductActivity.this, maps, R.layout.prodect_list, from, to);
        listView.setAdapter(simpleAdapter);
    }

    /**
     * 更新下拉列表框
     */
    public void updateSpinnerList() {
        List<Entrepot> entrepotList1 = entrepotDao.findEntrepotList();
        ArrayList<Map<String, Object>> maps = new ArrayList<>();
        for (Entrepot entrepot : entrepotList1) {
            HashMap<String, Object> stringObjectHashMap = new HashMap<>();
            stringObjectHashMap.put("spinnerEntrepotName", entrepot.getEntrepotName());
            stringObjectHashMap.put("spinnerEntrepotId", entrepot.getId());
            maps.add(stringObjectHashMap);
        }
        String[] from = {"spinnerEntrepotName", "spinnerEntrepotId"};
        int[] to = {R.id.spinnerEntrepotName, R.id.spinnerEntrepotId};
        SimpleAdapter simpleAdapter = new SimpleAdapter(addProductActivity.this, maps, R.layout.spinner_view, from, to);
        product_list.setAdapter(simpleAdapter);
    }
}